#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import subprocess
import user
import MySQLdb
import re
import sys
from xgoogle.search import GoogleSearch, SearchError

db = MySQLdb.connect(db = "megabase", user='root', passwd = "OhGheiw8EichahGh")

curTotal = db.cursor()
curTotal.execute("SELECT count(*) FROM `adresses` WHERE `categorie`=5 AND `bounced`=0 AND `internet`=0")
nb_total = curTotal.fetchone()[0]
curTotal.close()
print(str(nb_total) + " enregistrements a traiter\n")

cur = db.cursor()
cur.execute("SELECT `adresse` FROM `adresses` WHERE `categorie`=5 AND `bounced`=0 AND `internet`=0")
round = cur.fetchone()

count = 0

while round != None:

    current_email = round[0]

    if str(count)[len(str(count)) - 2:] == "00":
        db.commit()

    count = count + 1

    if count == 1 or str(count)[len(str(count)) - 2:] == "01":
        print("Traitement de l'enregistrement " + str(count) + "/" + str(nb_total))

    found = 0
    try:
        gs = GoogleSearch(current_email)
        gs.results_per_page = 5
        results = gs.get_results()
        for result in results:
            if re.search(round[0], result.title, re.I) or re.search(current_email, result.desc, re.I):
                    found = 1
                    break
        if found != 0:
            curExec = db.cursor()
            curExec.execute("UPDATE `adresses` SET `internet`=1 WHERE `adresse`='" + current_email + "' AND `internet`=0")
            curExec.close()
    except SearchError, e:
        print("Search failed : %s" % e)
        print("Ip adress : " + current_email)

    round = cur.fetchone()

cur.close()

db.commit()

sys.exit(0)
